<template>
    <el-container>
        <el-header style="text-align: right; font-size: 15px" height="50px">
            <el-row type="flex" justify="end">
                <el-col :xs="0" :sm="8" :md="4" :lg="4" :xl="4">
                    <el-input
                            v-model="search"
                            size="medium"
                            placeholder="输入宿舍号关键字搜索"/>
                </el-col>
                <el-col :xs="22" :sm="14" :md="4" :lg="4" :xl="4">
                    <el-dropdown size="medium" split-button type="primary" trigger="click" @command="handleCommand">
                        <i :disabled="current_building==null" class="fa fa-bars"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :disabled="current_building==null" command="new">新增</el-dropdown-item>
                            <el-dropdown-item :disabled="current_dorm==null" command="update">更新</el-dropdown-item>
                            <el-dropdown-item :disabled="current_dorm==null" command="delete">删除</el-dropdown-item>
                            <el-dropdown-item  command="updateBatch">批量更新</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span>{{current_dorm?current_dorm.code:''}}</span>
                </el-col>
            </el-row>
        </el-header>
        <el-table
                v-loading="loading2"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                @selection-change="handleSelectionChange"
                style="width:100%;"
                :data="dorms.filter(data => !search || data.code.toLowerCase().includes(search.toLowerCase()))"
                height="800px" row-class-name="myRowStyle" @row-click="rowclick">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column prop="code" label="宿舍号" width="100" sortable>
            </el-table-column>
            <el-table-column prop="unit_name" label="单元" width="80" sortable>
            </el-table-column>
            <el-table-column prop="beds" label="床位数" width="80">
            </el-table-column>
            <el-table-column prop="staff_count" label="入住人数" sortable width="100">
                <template slot-scope="scope">
                    <router-link tag="a" :to="'/dorm_list/'+building_id+'/dorm_arrange/'+scope.row.id"
                                 v-text="scope.row.staff_count">
                    </router-link>
                </template>
            </el-table-column>
            <el-table-column prop="bed_rent" label="住宿费">
            </el-table-column>
            <el-table-column prop="rent" label="房租">
            </el-table-column>
            <el-table-column prop="for_gender" label="类型" sortable>
                <template slot-scope="scope">
                    <label class="label label-warning fa fa-female" v-show="scope.row.for_gender==0">女</label>
                    <label class="label label-primary fa fa-male" v-show="scope.row.for_gender==1">男</label>
                    <label class="label label-info fa fa-heart" v-show="scope.row.for_gender==2">夫妻</label>
                    <label class="label label-danger fa fa-question"
                           v-show="scope.row.for_gender==3">未指定</label>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                    <label class="label label-danger" v-show="scope.row.status==0">未使用</label>
                    <label class="label label-success" v-show="scope.row.status==1">使用中</label>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <router-link tag="a" class="btn btn-primary"
                                 :to="'/dorm_list/'+building_id+'/dorm_meter/'+scope.row.id">抄表
                    </router-link>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog :title="(current_building==null?'':current_building.name)+oprtName+'宿舍'" width="40%"
                   :visible.sync="dialogFormVisible">
            <el-form :model="form" v-loading="loading" :rules="rules" ref="form">
                <el-form-item label="单元" :label-width="formLabelWidth" prop="unit_name">
                    <el-input v-model="form.unit_name" autocomplete="off" @change="concatCode()"
                              ></el-input>
                </el-form-item>
                <el-form-item label="楼层" :label-width="formLabelWidth" prop="floor">
                    <el-col :span="4">
                        <el-input-number v-model="form.floor" :min="1" :max="floors"
                                         @change="concatCode()" :disabled="isBatchUpdate"></el-input-number>
                    </el-col>
                </el-form-item>
                <el-form-item label="宿舍号" :label-width="formLabelWidth" prop="code">
                    <el-input v-model="form.code" autocomplete="off" :disabled="isBatchUpdate"></el-input>
                </el-form-item>
                <el-form-item label="宿舍租金(元)" :label-width="formLabelWidth" prop="rent">
                    <el-col :span="4">
                        <el-input-number v-model="form.rent" :min="0" :max="2000"
                                         @change="computeBedRent()"></el-input-number>
                    </el-col>
                </el-form-item>
                <el-form-item label="床位数" :label-width="formLabelWidth" prop="beds">
                    <el-col :span="4">
                        <el-input-number v-model="form.beds" :min="1" :max="10"
                                         @change="computeBedRent()"></el-input-number>
                    </el-col>
                </el-form-item>
                <el-form-item label="住宿费(元)" :label-width="formLabelWidth" prop="bed_rent">
                    <el-col :span="4">
                        <el-input-number v-model="form.bed_rent" :min="0" :max="1000"></el-input-number>
                    </el-col>
                </el-form-item>
                <el-form-item label="类型" :label-width="formLabelWidth" prop="for_gender">
                    <el-radio-group v-model="form.for_gender">
                        <el-radio :label="0">女宿舍</el-radio>
                        <el-radio :label="1">男宿舍</el-radio>
                        <el-radio :label="2">夫妻房</el-radio>
                        <el-radio :label="3">未指定</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="使用状态" :label-width="formLabelWidth" prop="status">
                    <el-col :span="6">
                        <el-select v-model="form.status" placeholder="请选择使用状态">
                            <el-option label="使用中" :value="1"></el-option>
                            <el-option label="未使用" :value="0"></el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                    <el-input v-model="form.remark" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlDorm">{{oprtName}}</el-button>
            </div>
        </el-dialog>
        <router-view @dormUpdated="handleDormUpdate()"></router-view>
    </el-container>
</template>
<script>
    export default{
        props: ['building_id'],
        data(){
            return {
                current_building: null,
                floors: 6,
                dorms: [],
                current_dorm: null,
                search: '',
                loading: false,
                loading2: false,
                form: {
                    building_id: '',
                    floor: '',
                    code: '',
                    unit_name: '1',
                    rent: '',
                    beds: '',
                    bed_rent: '',
                    for_gender: 3,
                    status: 1,
                    remark: ''
                },
                dialogFormVisible: false,
                isEdit: false,
                isBatchUpdate: false,
                oprtName: '添加',
                formLabelWidth: '100px',
                rules: {
                    unit_name:[
                        {required: true, message: '请务必填写所属单元', trigger: 'blur'},
                    ],
                    code: [
                        {required: true, message: '必填项', trigger: 'blur'}
                    ]
                },

                selectedIds:[],
                copyIds:[],
            }
        },
        created(){
            this.getdorms(this.building_id);
        },
        watch: {
            'building_id': function (newVal, oldVal) {
                this.getdorms(newVal);
            }
        },
        methods: {
            getdorms(building_id){
                this.$emit('emitindex');//解决人为刷新页面时，默认选中宿舍菜单失去焦点
                this.loading2 = true;
                axios.get('api/v1/building/' + building_id).then(result => {
                        this.current_building = result.data;
                        if (this.current_building) {
                            this.form.building_id = this.current_building.id;
                            this.form.rent = this.current_building.general_room_rent;
                            this.form.beds = this.current_building.beds_per_room;
                            this.form.bed_rent = this.current_building.general_room_rent / this.current_building.beds_per_room;
                            this.floors = this.current_building.floors;

                            axios.get('api/v1/dorm?building=' + building_id).then(
                                result => {
                                    this.dorms = result.data;
                                }
                            );
                            this.current_dorm = null;
                            this.loading2 = false;
                        }
                    }
                );
            },
            concatCode(){
                if (/^\d+/.test(this.current_building.name)) {
                    this.form.code = this.current_building.name + '#' + this.form.unit_name + 'D' + this.form.floor;
                } else {
                    this.form.code = this.current_building.name + this.form.floor;
                }
            },
            computeBedRent(){
                this.form.bed_rent = this.form.rent / this.form.beds;
            },
            handlDorm(){
                this.loading = true;

                if (this.isBatchUpdate) {
                    var batchUpdate={ids:this.copyIds,updateData:{
                        unit_name:this.form.unit_name,
                        rent:this.form.rent,
                        beds:this.form.beds,
                        bed_rent:this.form.bed_rent,
                        for_gender:this.form.for_gender,
                        status:this.form.status,
                        remark:this.form.remark
                    }};
                    axios.put('api/v1/dorm/'+this.building_id+'/batchUpdate', batchUpdate)
                        .then(result => {
                            if (result.error) {
                                this.$notify.error({message: '批量更新宿舍失败'});
                            } else {
                                this.$notify.success({message: '批量更新宿舍成功'});
                                this.getdorms(this.current_building.id);
                            }
                        })
                        .catch(error => {
                            if(error.response){
                                console.log(error.response);
                            }
                            this.$notify.error({
                                message: '发生异常,批量更新宿舍失败'
                            });
                        });
                } else {
                    if (this.isEdit) {
                        axios.put('api/v1/dorm/' + this.current_dorm.id, this.form)
                            .then(result => {
                                if (result.error) {
                                    this.$notify.error({message: '更新宿舍失败'});
                                } else {
                                    this.$notify.success({message: '更新宿舍成功'});
                                    this.getdorms(this.current_building.id);
                                }
                            })
                            .catch(error => {
                                if(error.response)console.log(error.response);
                                this.$notify.error({
                                    message: '发生异常,更新宿舍失败',
                                });
                            });
                    } else {
                        axios.post('api/v1/dorm', this.form).then(result => {
                            if (result.error) {
                                this.$notify.error({
                                    message: '创建宿舍失败',
                                });

                            } else {
                                this.$notify.success({
                                    message: '创建宿舍成功',
                                });
                                this.$refs['form'].resetFields();
                                this.getdorms(this.current_building.id);

                            }
                        }).catch(error => {
                            if(error.response){
                                console.log(error.response);
                        }
                            this.$notify.error({
                                message: '发生异常,创建宿舍失败',
                            });
                        });
                    }
                }
                this.loading = false;
                this.dialogFormVisible = false;
            },
            deleDorm(){
                this.$confirm('确认删除'+this.current_dorm.code,'删除提示').then(
                    ()=>{
                    axios.delete('api/v1/dorm/' + this.current_dorm.id, this.form)
                    .then(result => {
                    if (result.error) {
                    this.$notify.error({
                        message: '删除宿舍失败'
                    });

                } else {
                    this.$notify.success({
                        message: '删除宿舍成功'
                    });
                    this.getdorms(this.current_building.id);
                }
            })
            .catch(error => {
                    if(error.response){
                    console.log(error.response);
                }
                this.$notify.error({
                    message: '发生异常,删除宿舍失败',
                });
            });
                }
                ).catch(action=>{console.log(action);});

            },
            rowclick(row){
                this.current_dorm = row;
            },
            forGenderFmt(row, column){
                if (row.for_gender == 0) {
                    return '女宿舍';
                } else if (row.for_gender == 1) {
                    return '男宿舍';
                } else if (row.for_gender == 2) {
                    return '夫妻房';
                } else {
                    return '未指定';
                }
            },
            handleDormUpdate(){
                this.getdorms(this.building_id);
            },

            handleCommand(cmd){
                switch (cmd) {
                    case 'new':
                        this.isBatchUpdate = false;
                        this.isEdit = false;
                        this.oprtName = '添加';
                        this.dialogFormVisible = true;
                        break;
                    case 'update':
                        this.isBatchUpdate = false;
                        this.isEdit = true;
                        this.oprtName = '更新';
                        this.form = this.current_dorm;
                        this.dialogFormVisible = true;
                        break;
                    case 'updateBatch':
                        if(this.selectedIds.length<1){
                            this.copyIds=_.cloneDeep(this.selectedIds);//dialog弹出以后this.selectedIds中的数据被清除
                            this.$alert('请选择要更新的数据');
                            return;
                        }
                        this.isBatchUpdate = true;
                        this.isEdit = true;
                        this.oprtName = '批量更新';
                        this.dialogFormVisible = true;
                        break;
                    case 'delete':
                        this.deleDorm();
                        break;
                }
            },
            handleSelectionChange(val) {
                this.selectedIds = val.map(function (o) {
                    return o.id;
                });
            }
        }
    }
</script>
